package com.laicunba.service.accounting.impl;

import java.math.BigDecimal;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.service.AccountService.ACCOUNTING_SUBJECT;
import com.laicunba.service.AccountService.RECHARGE_WAY;
import com.laicunba.service.accounting.AccountingException;
import com.laicunba.service.accounting.AccountingTemplate;
import com.laicunba.service.accounting.RechargeAccountingService;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.StringUtil;

@Service
public class RechargeAccountingServiceImpl extends AccountingTemplate implements RechargeAccountingService {

	@Transactional
	@Override
	public synchronized String doRecharge(String userId, RECHARGE_WAY way, BigDecimal amount, String certificateId, String ext, String remark) {
		AssertUtil.assertTrue(theWholeBalanceIsZero(), AccountingException.BALANCE_SHEET_BEFORE_ACCOUNTING_ERROR);
		// 用户借记
		ACCOUNTING_SUBJECT drSubject = null;
		if (way == RECHARGE_WAY.ALIPAY) {
			drSubject = ACCOUNTING_SUBJECT.USER_CURRENCY_ALIPAY;
		} else if (way == RECHARGE_WAY.WEIXIN) {
			drSubject = ACCOUNTING_SUBJECT.USER_CURRENCY_WEIXIN;
		}
		AssertUtil.assertNotNull(drSubject);
		StringBuffer totalSignBuffer = new StringBuffer();
		String sign = makeUserDr(userId, drSubject, amount, certificateId, ext, remark);
		totalSignBuffer.append(sign);
		AssertUtil.assertNotNull(sign);

		// 用户贷记
		ACCOUNTING_SUBJECT crSubject = ACCOUNTING_SUBJECT.USER_BALANCE;
		sign = makeUserCr(userId, crSubject, amount, certificateId, ext, remark);
		totalSignBuffer.append(sign);

		// 平台借记
		ACCOUNTING_SUBJECT drPlatformSubject = null;
		if (way == RECHARGE_WAY.ALIPAY) {
			drPlatformSubject = ACCOUNTING_SUBJECT.CURRENCY_ALIPAY;
		} else if (way == RECHARGE_WAY.WEIXIN) {
			drPlatformSubject = ACCOUNTING_SUBJECT.CURRENCY_WEIXIN;
		}
		sign = makePlatformDr(drPlatformSubject, amount, certificateId, ext, remark);
		totalSignBuffer.append(sign);
		// 平台贷记
		sign = makePlatformCr(ACCOUNTING_SUBJECT.BALANCE, amount, certificateId, ext, remark);
		totalSignBuffer.append(sign);
		AssertUtil.assertTrue(theWholeBalanceIsZero(), AccountingException.BALANCE_SHEET_AFTER_ACCOUNTING_ERROR);
		return StringUtil.md5(totalSignBuffer.toString());
	}

}
